﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace MotoGame.Core
{
    class CollisionDetector
    {
        #region Properties
        IList<Sprite> sprites;
        public IList<Sprite> Sprites
        {
            get { return sprites; }
            set { sprites = value; }
        }
        #endregion

        #region Events
        public event EventHandler<CollisionEventArgs> OnHit;
        #endregion

        #region Constructors
        public CollisionDetector()
        {
            Sprites = new List<Sprite>();
        }
        #endregion

        #region Operations
        public void Update(GameTime gameTime)
        {
            for (int i = 0; i < sprites.Count; i++)
            {
                Sprite first = Sprites[i];
                for (int j = i + 1; j < sprites.Count; j++)
                {
                    Sprite last = Sprites[j];

                    Rectangle firstHitbox = new Rectangle(first.Colisao.X, first.Colisao.Y, first.Colisao.Width, first.Colisao.Height);
                    firstHitbox.Offset((int)first.Posicao.X, (int)first.Posicao.Y);
                    Rectangle lastHitbox = new Rectangle(last.Colisao.X, last.Colisao.Y, last.Colisao.Width, last.Colisao.Height);
                    lastHitbox.Offset((int)last.Posicao.X, (int)last.Posicao.Y);

                    if(firstHitbox.Intersects(lastHitbox))
                    {
                        OnHit(this, new CollisionEventArgs(first, last));
                    }
                }
            }
        }
        #endregion
    }

    public class CollisionEventArgs : EventArgs
    {
        Sprite first;
        public Sprite First
        {
            get { return first; }
            private set { first = value; }
        }

        Sprite last;
        public Sprite Last
        {
            get { return last; }
            private set { last = value; }
        }

        public CollisionEventArgs(Sprite first, Sprite last)
        {
            First = first;
            Last = last;
        }
    }
}
